<template>
  <div class="login-container">
    <el-form :model="user" ref="refForm" :rules="loginFormRules" class="login-form" >
      <h2 class="login-title">扶贫助农平台</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="user.username" ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" @click="submitForm('refForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      loginFormRules: {
        username: [
          // 表示当鼠标失去焦点的时候，验证，必填项，如果为空，则显示message中的内容
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 3, max: 10, message: "用户名3-10位", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      // 预验证  如果表单验证通过，则允许发送登录请求。如果验证不通过直接截止代码运行
      this.$refs.refForm.validate( async vaild => {
        //如果表单验证通过，valid的值会被传递为true,否则为false
        if (vaild) {
          let params = new URLSearchParams()
          params.append('username',this.user.username)
          params.append('password',this.user.password)
          //发送post请求
          let {data:res} = await this.$axios.post("/user/login",params)
          window.console.log(res)
          if(res.code == 200){
            this.$message.success('登录成功')
          //将token保存到sessionStorage
            window.sessionStorage.setItem('token',res.data.token)
            //如果sessionStoarge不为空，则跳转到主页
            this.$router.push('/index')
          } else {
            this.$message.error("用户名或密码不正确")
          }
        }else{
          window.console.log('error submit!!!')
          return false
        }

      })
      
    },
    resetForm(formName) {
        this.$refs[formName].resetFields();
      }
  },
};
</script>

<style lang="scss" scoped>
/*scoped:当前样式,不继承*/
.login-container {
  position: absolute;
  width: 100%;
  height: 100%;
  background: black;
}
.login-form {
  width: 30%;
  margin: 100px auto;
  background-color: #909090;
  border-radius: 20px;
  padding: 20px;
}
.login-title {
  color: #333;
}
</style>
